//
//  RankViewController.h
//  ksjv2
//
//  Created by mac on 14/12/18.
//  Copyright (c) 2014年 CnbizMedia. All rights reserved.
//

#import "ProfileViewController.h"
#import "AppDelegate.h"
@interface ProfileViewController ()<UITextFieldDelegate,UIAlertViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>{
    NSString*pasw;

}
@property (weak, nonatomic) IBOutlet UIButton *sexWoman;
@property (weak, nonatomic) IBOutlet UIButton *sexMan;
@property (weak, nonatomic) IBOutlet UIButton *changePas;
@property (weak, nonatomic) IBOutlet UIButton *userExit;

@property (strong,nonatomic) NSString * sex;
@property (weak, nonatomic) IBOutlet UILabel *name;
@property (weak, nonatomic) IBOutlet UITextField *nike;
@property (weak, nonatomic) IBOutlet UITextField *emali;
@property (weak, nonatomic) UITextField *Signature;
@property (weak, nonatomic) IBOutlet UIButton *BindingPhone;
@property (weak, nonatomic) IBOutlet UIImageView *icon;
@end
///编辑资料
@implementation ProfileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"编辑资料";
    self.view.backgroundColor=UIColorFromRGB(0xf5f5f5);
    
    [self setupRightMenuButton];
    // Do any additional setup after loading the view.
    
}
-(void)viewWillAppear:(BOOL)animated{
    [self loadData];
}
-(void)loadData{
    NSDictionary*dic=[UserDefaults objectForKey:@"user"];
    
    UIImageView*imageview=(UIImageView*)[self.view viewWithTag:10];

    [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:dic[@"thumb"][@"180"]] options:SDWebImageRefreshCached progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        if (image==nil) {
            [imageview setImage:[UIImage imageNamed:@"icon_default_ipad"]];
        }else{
            [imageview setImage:image];
        }
    }];
    self.emali.text=dic[@"email"];

    UILabel * leftView = [[UILabel alloc] initWithFrame:CGRectMake(10,0,10,26)];
    leftView.backgroundColor = [UIColor clearColor];
    self.emali.leftView = leftView;
    self.emali.leftViewMode = UITextFieldViewModeAlways;
    self.emali.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    self.nike.text=dic[@"nickname"];
    UILabel * leftView2 = [[UILabel alloc] initWithFrame:CGRectMake(10,0,10,26)];
    leftView2.backgroundColor = [UIColor clearColor];
    self.nike.leftView = leftView2;
    self.nike.leftViewMode = UITextFieldViewModeAlways;
    self.nike.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
    UILabel * leftView3 = [[UILabel alloc] initWithFrame:CGRectMake(10,0,10,26)];
    leftView3.backgroundColor = [UIColor clearColor];
    self.Signature=(UITextField*)[self.view viewWithTag:333];
    self.Signature.leftView = leftView3;
    self.Signature.leftViewMode = UITextFieldViewModeAlways;
    self.Signature.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    self.Signature.text=dic[@"signature"];
    
    UILabel*label=(UILabel*)[self.view viewWithTag:111];
    label.text=dic[@"username"];
    
    self.sex=[NSString stringWithFormat:@"%@",dic[@"sex"]];
    if ([dic[@"mobile"] length]>5) {
        [self.BindingPhone setTitle:dic[@"mobile"] forState:UIControlStateNormal];
    }
    [self.changePas.layer setCornerRadius:10];
    [self.changePas.layer setMasksToBounds:YES];
    
    [self.userExit.layer setCornerRadius:10];
    [self.userExit.layer setMasksToBounds:YES];
    
    [self.icon.layer setCornerRadius:30];
    [self.icon.layer setMasksToBounds:YES];
    
}
-(void)setupRightMenuButton{
    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(0, 0, 40, 40)];
    [button setTitle:@"保存" forState:UIControlStateNormal];
//    [button setImage:[UIImage imageNamed:@"sou"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(DoneAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem*rightBarItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.rightBarButtonItem=rightBarItem;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self resignFirst];
}
-(void)resignFirst{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}
#pragma mark - Action
- (IBAction)sexM:(id)sender {
    self.sex=@"1";
}
- (IBAction)sexW:(id)sender {
    self.sex=@"0";
}

-(void)setSex:(NSString *)sex{
    if (sex!=nil) {
        if (![sex isEqualToString:@"0"]) {
            [self.sexMan setImage:[UIImage imageNamed:@"icoyes"] forState:UIControlStateNormal];
            [self.sexWoman setImage:[UIImage imageNamed:@"icono"] forState:UIControlStateNormal];
            _sex=@"1";
        }else{
            [self.sexWoman setImage:[UIImage imageNamed:@"icoyes"] forState:UIControlStateNormal];
            [self.sexMan setImage:[UIImage imageNamed:@"icono"] forState:UIControlStateNormal];
            _sex=@"0";
        }
    }
    
}

- (IBAction)BindingPhone:(id)sender {
    [self performSegueWithIdentifier:@"Binding" sender:self];
}

- (IBAction)iconAction:(id)sender {
}
- (IBAction)RPassAction:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"密码修改" message:@"请输入新密码:" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定修改", nil];
    [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [alert setTag:3];
    [alert show];
}
- (IBAction)exit:(id)sender {
    //AppDelegate*app=APPDelegate;
    //app.BadgeStr=@"0";
    [[AppAPIClient sharedClient] setTokenA:@""];
    //[BPush delTag:[UserDefaults objectForKey:@"token"]];
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"token"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"user"];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (IBAction)upIcon:(id)sender {
    [self resignFirst];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"头像设置" message:@"请选择头像来源." delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"拍照",@"相册中选取", nil];
    [alert setTag:1];
    [alert show];

}

-(void)DoneAction{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    if (self.nike.text.length<2) {
        [alert setMessage:@"昵称长度过短"];
        [alert show];
        return;
    }else if (self.emali.text.length<5){
        [alert setMessage:@"邮箱长度过短"];
        [alert show];
        return;
    }else if (![CommonHelper isValidateEmail:self.emali.text]){
        [alert setMessage:@"邮箱格式不正确"];
        [alert show];
        return;
    }else if (pasw.length!=0&&pasw.length<6){
        [alert setMessage:@"新密码长度过短"];
        [alert show];
        return;
    }
    NSString*str_signature;
    if (self.Signature.text.length>12) {
        str_signature=[self.Signature.text substringToIndex:12];
    }else{
        str_signature=self.Signature.text;
    }
    NSDictionary*dic=[NSDictionary dictionaryWithObjectsAndKeys:self.sex,@"sex",self.nike.text,@"nickname",self.emali.text,@"email",str_signature,@"Signature", nil];
    [SVProgressHUD show];
    [[AppAPIClient sharedClient] POST:@"User/Update" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSMutableDictionary*dic=[NSMutableDictionary dictionaryWithDictionary:IFUserLogin];
        [dic setObject:self.nike.text forKey:@"nickname"];
        [dic setObject:self.emali.text forKey:@"email"];
        [dic setObject:self.sex forKey:@"sex"];
        [dic setObject:str_signature forKey:@"signature"];
        [UserDefaults setObject:dic forKey:@"user"];
        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"ERR: %@",operation.responseString);
        [SVProgressHUD showErrorWithStatus:@"保存失败"];
    }];
}

#pragma mark - delegeta
- (void)uploadUserhead:(UIImage*)image{
    
    [[AppAPIClient sharedClient] POST:@"User/UploadAvatar" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSData *data = UIImageJPEGRepresentation(image, 0.1);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        
        [formData appendPartWithFileData:data name:@"image" fileName:fileName mimeType:@"image/png"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success:%@",responseObject);
        NSString *url = [NSString stringWithFormat:@"%@",[UserDefaults objectForKey:@"user"][@"thumb"][@"180"]];
        [[SDImageCache sharedImageCache] removeImageForKey:url];
        [[SDImageCache sharedImageCache] storeImage:image forKey:url];
        [self.icon setImage:image];
        
        [self.navigationController popViewControllerAnimated:YES];
        [SVProgressHUD showSuccessWithStatus:LOADING_TEXT_SUCCESS];
        [self dismissViewControllerAnimated:YES completion:NULL];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error:%@ => %@",operation.responseString,error);
        [SVProgressHUD showErrorWithStatus:LOADING_TEXT_ERROR];
        [self dismissViewControllerAnimated:YES completion:NULL];
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [self dismissViewControllerAnimated:YES completion:^{
        [SVProgressHUD show];
    UIImage *image= [info objectForKey:@"UIImagePickerControllerEditedImage"];
    [self uploadUserhead:image];
    }];
    

}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    //[self popoverPresentationController];
    [self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//    NSLog(@"btn:%d",buttonIndex);
    if(alertView.tag == 1){
        if(buttonIndex == 2){
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
//            imagePickerController.modalPresentationStyle   = UIModalPresentationCurrentContext;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing            = YES;
            //imagePickerController.showsCameraControls = NO;
            [self presentViewController:imagePickerController animated:YES completion:NULL];
        }else if(buttonIndex == 1){
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
//            imagePickerController.modalPresentationStyle   = UIModalPresentationCurrentContext;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing            = YES;
            imagePickerController.showsCameraControls = YES;
            [self presentViewController:imagePickerController animated:YES completion:NULL];
        }else{
            [alertView dismissWithClickedButtonIndex:0 animated:YES];
        }
    }else{
    if (buttonIndex==1) {
        pasw=[alertView textFieldAtIndex:0].text;
        if (pasw.length>0) {
            
        
        [[AppAPIClient sharedClient] POST:@"User/Update" parameters:@{@"password":[alertView textFieldAtIndex:0].text} success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [SVProgressHUD showSuccessWithStatus:@"密码修改成功"];
            [self.navigationController popViewControllerAnimated:YES];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"ERR: %@",operation.responseString);
            [SVProgressHUD showErrorWithStatus:@"修改失败"];
        }];
        }else{
            [SVProgressHUD showErrorWithStatus:@"密码不能为空"];
        }
      }
    }
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if (textField.tag==333) {
        [UIView animateWithDuration:.3 animations:^{
            self.view.window.frame=CGRectMake(0, self.view.window.frame.origin.y-40, self.view.window.frame.size.width, self.view.window.frame.size.height);
        }];
    }
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag==333) {
        
        [UIView animateWithDuration:.3 animations:^{
            self.view.window.frame=CGRectMake(0, self.view.window.frame.origin.y+40, self.view.window.frame.size.width, self.view.window.frame.size.height);
        } completion:^(BOOL finished) {
            if (textField.text.length>12) {
                SHOW_ALERT(@"您的签名过长", @"请控制在12字以内");
            }
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
